package org.dromara.comm_lhz.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.dromara.comm_lhz.config.PointsConfig;
import org.dromara.comm_lhz.entity.AsPointsManagementEntity;
import org.dromara.comm_lhz.mapper.AsPointsManagementHMapper;
import org.dromara.comm_lhz.param.PointsPageParam;
import org.dromara.comm_lhz.service.AsPointsManagementHService;
import org.dromara.comm_lhz.util.Result;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.data.domain.Pageable;
import org.flowable.idm.engine.impl.persistence.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 积分管理服务实现类
 */
@Service

public class AsPointsManagementHHServiceImpl extends ServiceImpl<AsPointsManagementHMapper, AsPointsManagementEntity> implements AsPointsManagementHService {
    @Autowired
    private AsPointsManagementHMapper asPointsManagementHMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    private final PointsConfig pointsConfig;

    @Autowired
    public AsPointsManagementHHServiceImpl(PointsConfig pointsConfig) {
        this.pointsConfig = pointsConfig;
    }


    /**
     * 查询积分信息
     *
     * @param nickName 分页查询参数
     * @return 分页数据，包含积分信息
     */
    @Override
    public Page<AsPointsManagementEntity> selPoints(String nickName, Pageable pageable) {
        // 创建分页对象，页码从1开始
        Page<SysUser> sysUserPage = new Page<>(pageable.getPageNumber() + 1, pageable.getPageSize());

        // 创建查询条件
        LambdaQueryWrapper<SysUser> userQueryWrapper = new LambdaQueryWrapper<>();
        if (nickName != null && !nickName.isEmpty()) {
            // 添加nickName模糊查询条件
            userQueryWrapper.like(SysUser::getNickName, nickName);
        }

        // 分页查询符合条件的SysUser
        Page<SysUser> pageSysUserResult = sysUserMapper.selectPage(sysUserPage, userQueryWrapper);

        // 获取所有符合条件的userId
        List<Long> userIds = pageSysUserResult.getRecords().stream()
            .map(SysUser::getUserId)
            .collect(Collectors.toList());

        // 创建积分管理信息的分页查询条件
        Page<AsPointsManagementEntity> pointsPage = new Page<>(pageable.getPageNumber() + 1, pageable.getPageSize());
        LambdaQueryWrapper<AsPointsManagementEntity> pointsQueryWrapper = new LambdaQueryWrapper<>();
        if (!userIds.isEmpty()) {
            // 根据userIds查询AsPointsManagementEntity
            pointsQueryWrapper.in(AsPointsManagementEntity::getUserId, userIds);
        }

        // 分页查询积分管理信息
        Page<AsPointsManagementEntity> resultPage = asPointsManagementHMapper.selectPage(pointsPage, pointsQueryWrapper);

        // 对每个结果进行处理，查询SysUser信息
        for (AsPointsManagementEntity management : resultPage.getRecords()) {
            LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(SysUser::getUserId, management.getUserId());
            List<SysUser> sysUsers = sysUserMapper.selectList(userWrapper);
            // 将用户信息加入到management对象中
            management.setSysUsers(sysUsers);
        }

        // 返回分页结果
        return resultPage;
    }





    /**
     * 新建用户积分信息
     *
     * @param asPointsManagementEntity 积分实体信息
     * @return 影响的行数
     */
    @Override
    public int insert(AsPointsManagementEntity asPointsManagementEntity) {
        return asPointsManagementHMapper.insert(asPointsManagementEntity);
    }

    /**
     * 根据ID更新用户积分
     *
     * @param asPointsManagementEntity 积分实体信息
     * @return 更新是否成功
     */
    @Override
    public boolean updatePointsById(AsPointsManagementEntity asPointsManagementEntity) {
        AsPointsManagementEntity entity = asPointsManagementHMapper.selectById(asPointsManagementEntity.getId());

        if (entity != null) {
            entity.setIntegral(entity.getIntegral() + 1);
            return this.updateById(entity);
        } else return false;

    }


    /**
     * 用户消费   订单用 用来支付
     * @param userId
     * @param sumPrice
     */
    @Override
    public Result updatePointsPay(Long userId, Double sumPrice) {

        // 查询用户当前积分
        AsPointsManagementEntity userPointsEntity = this.getOne(
            new QueryWrapper<AsPointsManagementEntity>()
                .select(pointsConfig.getIntegral())
                .eq(pointsConfig.getUserId(), userId)
        );

        if (userPointsEntity == null) {
            return Result.error("用户不存在");
        }

        Double currentPoints = Double.valueOf(userPointsEntity.getIntegral());

        // 判断当前积分是否足够
        if (currentPoints < sumPrice) {
            return Result.error("当前积分不足");
        }

        // 更新用户积分
        boolean updateResult = this.update()
            .setSql(pointsConfig.getIntegral() + " = " + pointsConfig.getIntegral() + " - " + sumPrice)
            .eq(pointsConfig.getUserId(), userId)
            .update(null);

        if (!updateResult) {
            return Result.error("积分更新失败");
        }

        return Result.success("消费成功");
    }
}

